package cn.zurish.cloud.snow.tools;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * JSON文件解析并生成Excel的工具类
 */
public class JsonToExcelConverter {

    /**
     * 将JSON文件转换为Excel文件
     * @param jsonFilePath JSON文件路径
     * @param excelFilePath Excel文件路径
     * @throws IOException 文件操作异常
     */
    public static void convertJsonToExcel(String jsonFilePath, String excelFilePath) throws IOException {
        // 读取JSON文件
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(new File(jsonFilePath));

        // 解析JSON数据
        List<Map<String, Object>> dataList = parseJson(rootNode);

        // 生成Excel文件
        generateExcel(dataList, excelFilePath);
    }

    /**
     * 解析JSON数据为Map列表
     * @param rootNode JSON根节点
     * @return 解析后的Map列表
     */
    private static List<Map<String, Object>> parseJson(JsonNode rootNode) {
        List<Map<String, Object>> dataList = new ArrayList<>();

        // 判断JSON类型
        if (rootNode.isArray()) {
            // 处理JSON数组
            for (JsonNode node : rootNode) {
                if (node.isObject()) {
                    dataList.add(parseJsonObject(node));
                }
            }
        } else if (rootNode.isObject()) {
            // 处理单个JSON对象
            dataList.add(parseJsonObject(rootNode));
        }

        return dataList;
    }

    /**
     * 解析JSON对象为Map
     * @param node JSON节点
     * @return 解析后的Map
     */
    private static Map<String, Object> parseJsonObject(JsonNode node) {
        Map<String, Object> map = new LinkedHashMap<>();

        Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> field = fields.next();
            String key = field.getKey();
            JsonNode valueNode = field.getValue();

            Object value = null;
            if (valueNode.isValueNode()) {
                if (valueNode.isTextual()) {
                    value = valueNode.asText();
                } else if (valueNode.isNumber()) {
                    if (valueNode.isIntegralNumber()) {
                        value = valueNode.asLong();
                    } else {
                        value = valueNode.asDouble();
                    }
                } else if (valueNode.isBoolean()) {
                    value = valueNode.asBoolean();
                } else if (valueNode.isNull()) {
                    value = null;
                }
            } else if (valueNode.isArray()) {
                // 处理数组
                List<Object> arrayList = new ArrayList<>();
                for (JsonNode arrayNode : valueNode) {
                    if (arrayNode.isValueNode()) {
                        if (arrayNode.isTextual()) {
                            arrayList.add(arrayNode.asText());
                        } else if (arrayNode.isNumber()) {
                            if (arrayNode.isIntegralNumber()) {
                                arrayList.add(arrayNode.asLong());
                            } else {
                                arrayList.add(arrayNode.asDouble());
                            }
                        } else if (arrayNode.isBoolean()) {
                            arrayList.add(arrayNode.asBoolean());
                        } else if (arrayNode.isNull()) {
                            arrayList.add(null);
                        }
                    } else if (arrayNode.isObject()) {
                        arrayList.add(parseJsonObject(arrayNode));
                    }
                }
                value = arrayList;
            } else if (valueNode.isObject()) {
                // 处理嵌套对象
                value = parseJsonObject(valueNode);
            }

            map.put(key, value);
        }

        return map;
    }

    /**
     * 生成Excel文件
     * @param dataList 数据列表
     * @param excelFilePath Excel文件路径
     * @throws IOException 文件操作异常
     */
    private static void generateExcel(List<Map<String, Object>> dataList, String excelFilePath) throws IOException {
        if (dataList.isEmpty()) {
            return;
        }

        // 获取表头
        Map<String, Object> firstRow = dataList.get(0);
        List<String> headers = new ArrayList<>(firstRow.keySet());

        // 转换数据为List<List<Object>>格式
        List<List<Object>> excelData = new ArrayList<>();
        for (Map<String, Object> rowData : dataList) {
            List<Object> row = new ArrayList<>();
            for (String header : headers) {
                Object value = rowData.get(header);
                if (value != null) {
                    row.add(value.toString());
                } else {
                    row.add("");
                }
            }
            excelData.add(row);
        }

        // 转换表头为EasyExcel格式
        List<List<String>> excelHeaders = new ArrayList<>();
        for (String header : headers) {
            List<String> headerList = new ArrayList<>();
            headerList.add(header);
            excelHeaders.add(headerList);
        }

        // 设置表头样式
        WriteCellStyle headStyle = new WriteCellStyle();
        headStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
        headStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        headStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        WriteFont headFont = new WriteFont();
        headFont.setBold(true);
        headFont.setFontHeightInPoints((short) 12);
        headStyle.setWriteFont(headFont);

        // 设置内容样式
        WriteCellStyle contentStyle = new WriteCellStyle();
        contentStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 应用样式
        HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headStyle, contentStyle);

        // 写入Excel
        EasyExcel.write(excelFilePath)
                .head(excelHeaders)
                .registerWriteHandler(styleStrategy)
                .sheet("Data")
                .doWrite(excelData);
    }

    /**
     * 主方法，用于测试
     */
    public static void main(String[] args) {
        try {
            String jsonFilePath = "D:\\Code\\snow\\src\\main\\resources\\data\\data.json";
            String excelFilePath = "D:\\Code\\snow\\src\\main\\resources\\data\\output.xlsx";

            convertJsonToExcel(jsonFilePath, excelFilePath);
            System.out.println("JSON文件已成功转换为Excel文件：" + excelFilePath);
        } catch (IOException e) {
            System.err.println("转换过程中发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
